package com.batsoft.trade.api.core.shiro.util;

import com.batsoft.trade.api.core.shiro.CacheUser;
import com.batsoft.trade.api.common.constant.Constant;
import com.gomyb.redis.RedisService;
import com.gomyb.web.SpringContextUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.Subject;

import java.util.Set;

/**
 * @author <a href="mailto:hellohesir@gmail.com">Mr_He</a>
 */
public class ShiroUtil {

    private static RedisService redisService = SpringContextUtil.getBean("redisService");

    /**
     * 获得当前用户所有权限url
     */
    public static Set<String> getPermissions() {
        CacheUser user = getUser();
        if (null != user) {
            String username = user.getUsername();
            SimpleAuthorizationInfo simpleAuthorizationInfo = redisService.getObj(Constant.SHIRO_CACHE_PREFIX + username);
            if (null != simpleAuthorizationInfo) {
                return simpleAuthorizationInfo.getStringPermissions();
            }
        }
        return null;
    }

    /**
     * 获得当前用户所有角色
     */
    public static Set<String> getRoles() {
        CacheUser user = getUser();
        if (null != user) {
            String username = user.getUsername();
            SimpleAuthorizationInfo simpleAuthorizationInfo = redisService.getObj(Constant.SHIRO_CACHE_PREFIX + username);
            if (null != simpleAuthorizationInfo) {
                return simpleAuthorizationInfo.getRoles();
            }
        }
        return null;
    }

    /**
     * 获得用户名
     */
    public static String getUsername() {
        CacheUser user = getUser();
        if (null != user) {
            return user.getUsername();
        }
        throw new RuntimeException("no login...");
    }

    /**
     * 获得当前登录用户
     */
    public static CacheUser getUser() {
        Subject subject = SecurityUtils.getSubject();
        Object principal = subject.getPrincipal();
        if (null != principal) {
            return (CacheUser) principal;
        }
        return null;
    }

}
